//
//  ZYBaseVC.m
//  YiLin
//
//  Created by Zyark on 2018/5/29.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYBaseVC.h"
#import "MXNavigationBarManager.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "RHSocketService.h"
#import "RHSocketUtils+Protobuf.h"
#import "RHProtobufVarint32LengthEncoder.h"
#import "RHProtobufVarint32LengthDecoder.h"
#import "DeviceCommunicate.pbobjc.h"

@interface ZYBaseVC ()

@end

@implementation ZYBaseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLanguage) name:@"changeLanguage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectSocketServiceState:) name:kNotificationSocketServiceState object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectSocketPacketResponse:) name:kNotificationSocketPacketResponse object:nil];
    [self.view setBackgroundColor:[UIColor whiteColor]];
}

-(void)setupTap{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:tap];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)switchLanguage{
    NSString *language = [[ZYChangeLanguage sharedZYChangeLanguage] userLanguage];
    if ([language isEqualToString:@"en"]) {
        [[ZYChangeLanguage sharedZYChangeLanguage] setUserlanguage:@"zh-Hans"];
    }else{
        [[ZYChangeLanguage sharedZYChangeLanguage] setUserlanguage:@"en"];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeLanguage" object:self];
    [ZYConfig setIsInitLanguage:YES];//是否初始化语言
}

-(void)setLanguage:(NSString *)language{
    if (![language isEqualToString:@"en"]) {
        [[ZYChangeLanguage sharedZYChangeLanguage] setUserlanguage:@"zh-Hans"];
    }else{
        [[ZYChangeLanguage sharedZYChangeLanguage] setUserlanguage:@"en"];
    }
    [ZYConfig setIsInitLanguage:YES];//是否初始化语言
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeLanguage" object:self];
}

//透明导航栏
- (void)setupBarManager {
    //required
    [MXNavigationBarManager managerWithController:self];
    [MXNavigationBarManager setBarColor:[UIColor clearColor]];
    
    //optional
    [MXNavigationBarManager setTintColor:[UIColor blackColor]];
    [MXNavigationBarManager setStatusBarStyle:UIStatusBarStyleLightContent];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupBarManager];
    [self changeLanguage];
//    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [MXNavigationBarManager reStoreToSystemNavigationBar];
}

-(void)dismissKeyboard{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (void)changeLanguage{
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor clearColor]}];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)detectSocketServiceState:(NSNotification *)notif
{
    //NSDictionary *userInfo = @{@"host":host, @"port":@(port), @"isRunning":@(_isRunning)};
    //对应的连接ip和状态数据。_isRunning为YES是连接成功。
    //没有心跳超时后会自动断开。
    
    
    id state = notif.object;
    if (state && [state boolValue]) {
        //连接成功后，发送数据包
        NSLog(@"detectSocketServiceState: %@", notif);
        [self connectSocketSuccess:notif];
    } else {
        //
    }//if
}

-(void)connectSocketSuccess:(NSNotification *)notif{
    
}

- (void)detectSocketPacketResponse:(NSNotification *)notif
{
    NSLog(@"detectSocketPacketResponse: %@", notif);
    NSDictionary *userInfo = notif.userInfo;
    RHSocketPacketResponse *rsp = userInfo[@"RHSocketPacket"];
    device_communicate *msg = [device_communicate parseFromData:[rsp object] error:nil];
    if(!NULLString(msg.jsonStr)){
        NSData *jsonData = [msg.jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: jsonData options:NSJSONReadingAllowFragments error:nil];
        NSString *code = [dict objectForKey:@"code"];
        if([code integerValue] != 200){
            [[ToastHelper sharedToastHelper] toast:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:[NSString stringWithFormat:@"code_%@",code]]]; 
            return;
        }
    }
    [self receiveMsgData:msg];
}

-(void)receiveMsgData:(device_communicate *)data{
    
}

//重新连接socket
-(void)reconnectWithIp:(NSString *)ip macAddress:(NSString *)macAddress isDisconnect:(BOOL) isDisconnect{
    //连接socket
    NSString *host = ip;
    if(NULLString(host)){
        host = @"10.0.0.240";
    }
    if(!isDisconnect){
        if([[RHSocketService sharedInstance].connectParam.host isEqualToString:host] && [[RHSocketService sharedInstance] isRunning]){
            return;
        }
    }
    int port = 10002;
    //protocol buffer
    RHProtobufVarint32LengthEncoder *encoder = [[RHProtobufVarint32LengthEncoder alloc] init];
    RHProtobufVarint32LengthDecoder *decoder = [[RHProtobufVarint32LengthDecoder alloc] init];

    [RHSocketService sharedInstance].encoder = encoder;
    [RHSocketService sharedInstance].decoder = decoder;
    //设置心跳包
    RHSocketPacketRequest *req = [[RHSocketPacketRequest alloc] init];
    device_communicate *message = [[device_communicate alloc] init];
    message.module = 100;
    message.cmd = 0;
    message.sid = [ZYConfig loginToken];
    message.macAddress = macAddress;
    message.userId = [ZYConfig userId];
    req.object = [message data];
    RHSocketConnectParam *connectParam = [[RHSocketConnectParam alloc] init];
    connectParam.host = host;
    connectParam.port = port;
    connectParam.heartbeatInterval = 20;
    connectParam.autoReconnect = YES;
    [RHSocketService sharedInstance].heartbeat = req;
    if([[RHSocketService sharedInstance] isRunning]){
        [[RHSocketService sharedInstance] stopService];
    }
    [[RHSocketService sharedInstance] startServiceWithConnectParam:connectParam];
}

@end
